import jquery from "jquery"
let $ = jquery


let index = 0;//截取图片的次数
let dsq = null;
//开启/关闭 摄像头
$("button").click(function (){
    if($("button").text()=="开启摄像头"){
        //开启摄像头
        openMedia();
        $("button").text("关闭摄像头");
        //     随意截取5张图片
        dsq = setInterval(function(){
            index++;
            getPhone();
            if(index==5){
                clearInterval(dsq);
                closeMedia();
                $("button").text("开启摄像头");
                alert("验证失败，请重试")
            }
        },2000)

    }else{
        $("button").text("开启摄像头");
        clearInterval(dsq);
        closeMedia();
    }
});
//开启摄像头
const openMedia = function (){
    let constraints = {
        video: { width: 500, height: 500 },
        audio: false
    };
    //获得video摄像头
    let video = document.getElementById('video');
    let promise = navigator.mediaDevices.getUserMedia(constraints);
    promise.then((mediaStream) => {
        // mediaStreamTrack = typeof mediaStream.stop === 'function' ? mediaStream : mediaStream.getTracks()[1];
        mediaStreamTrack=mediaStream.getVideoTracks()
        video.srcObject = mediaStream;
        video.play();
    });
}


// 关闭摄像头
const closeMedia = function() {
    let stream = document.getElementById('video').srcObject;
    let tracks = stream.getTracks();
    tracks.forEach(function(track) {
        track.stop();
    });
    document.getElementById('video').srcObject = null;
}


//截取摄像头里的图片 ：暂时无法实现 获取摄像头里面的人脸。
//只能通过定时器：来定时截取摄像头里面的照片 然后提交给后台测试是否通过人脸识别

const getPhone = function (){
    // let video = document.getElementById('video');
    // let canvas = document.getElementById('canvas');
    let ctx = canvas.getContext('2d');
    ctx.drawImage(video, 0, 0, 500, 500);
    let img = document.getElementById('canvas').toDataURL();
    // 获取截取图片的base64编码
    let base64 = img.split(",")[1];

    $.ajax({
        "url" : "/FaceQueryServlet",  //这里必须要使用post 因为base64编码的长度过长
        "type":"post",
        //这里的list：表示从哪个小组查询人脸、可以根据项目需求，决定是否写死或写活
        "data":{"base64" : base64,"list":"group_1"},
        "dataType" : "json",
        "success" : function (data){
            let score = data.result.user_list[0].score;

            console.log(data)

            if (score>80){
                clearInterval(dsq);
                closeMedia();
                $("button").text("开启摄像头");
                alert("登录成功，你的用户id为" + data.result.user_list[0].user_id);
            }
        }
    });
}

const all = {openMedia,closeMedia,getPhone}
export default all